//
//  MYLoginViewController.m
//  投融保
//
//  Created by 523 on 13-12-16.
//  Copyright (c) 2013年 木叶科技. All rights reserved.
//

#import "MYLoginViewController.h"
#import "MYCustomTextField.h"
#import "MYRecommendViewController.h"
#import "ASIFormDataRequest.h"

#import "MYVerifyEmailViewController.h"

#import "Encryption.h"
#import "CRSA.h"
#import "NSData+NSData_HexAdditions.h"

#import "MYRegInfoViewController.h"
#import "MYWebService.h"
#import "ForgotPassWord.h"

@interface MYLoginViewController ()

@end


@implementation MYLoginViewController
@synthesize bgScrollView;
@synthesize txtLoginName;
@synthesize txtPassword;
@synthesize loginService;

NSDictionary *accountDic;//帐户状态  认证  余额
NSDictionary *userInformation ;//用户信息
NSDictionary *bankDic ;//用户信息
extern NSString *key;
extern bool loginFlag;
NSString *appKey;
int prewTag ;  //编辑上一个UITextField的TAG,
float prewMoveY; //编辑的时候移动的高度
extern NSDictionary *loginDic;
NSDictionary *userInformation;//帐户信息全局变量
NSString *userRole;//用户角色
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    
    SETBACKGROUND
    
    [self initView];
    
 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    [self.view setBackgroundColor:[UIColor blackColor]];
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
- (void)initView
{
    int _Y = 0;
    if (IOS_VERSION>=7.0) {
        _Y=20;
    }
    float viWidth = self.view.frame.size.width;
    UITapGestureRecognizer *tapGestur=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeybard)];
    bgScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0, _Y+105,SCREEN_WIDTH ,SCREEN_HEIGHT-_Y)];
    [bgScrollView setContentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-_Y+1)];
    [bgScrollView setDelegate:self];
    [bgScrollView addGestureRecognizer:tapGestur];
    [self.view addSubview:bgScrollView];
    
    UIView *titleView=[[UIView alloc] initWithFrame:CGRectMake(0, _Y, viWidth, 105)];
    [titleView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"titile_bg"]]];
    [self.view addSubview:titleView];

    UILabel *lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(250, 15, 268, 66)];
    [lblTitle setText:@"登录"];
    [lblTitle setTextColor:[UIColor whiteColor]];
    lblTitle.backgroundColor = [UIColor clearColor];
    [lblTitle setFont:[UIFont boldSystemFontOfSize:40]];
    lblTitle.textAlignment=NSTextAlignmentCenter;
    [titleView addSubview:lblTitle];
    
    UIButton *btnReturn=[UIButton new];
    [btnReturn setFrame:CGRectMake(0, 0, 105, 105)];
    [btnReturn setImage:[UIImage imageNamed:@"return_icon"] forState:UIControlStateNormal];
    [btnReturn.titleLabel setFont:[UIFont systemFontOfSize:11]];
    [btnReturn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnReturn addTarget:self action:@selector(btnReturnClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:btnReturn];
    UIImageView *logoImage=[[UIImageView alloc] initWithFrame:CGRectMake(209, 40+_Y, 350, 70)];
    logoImage.image=[UIImage imageNamed:@"logo"];
    [self.bgScrollView addSubview:logoImage];
    
    txtLoginName=[[MYCustomTextField alloc] initWithFrame:CGRectMake(24, 130+_Y, 721, 104)];
    [txtLoginName setPlaceholder:@"请输入您的账户名"];
    [txtLoginName setFont:[UIFont systemFontOfSize:33]];
    [txtLoginName setAutocorrectionType:UITextAutocorrectionTypeNo];
    txtLoginName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [txtLoginName setBackground:[UIImage imageNamed:@"textfild_bg"]];
    txtLoginName.delegate=self;
    [txtLoginName addTarget:self action:@selector(closeKeybard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [bgScrollView addSubview:txtLoginName];
    
    txtPassword=[[MYCustomTextField alloc] initWithFrame:CGRectMake(24, 254+_Y, 721, 104)];
    [txtPassword setFont:[UIFont systemFontOfSize:33]];
    [txtPassword setPlaceholder:@"请输入密码"];
    [txtPassword setAutocorrectionType:UITextAutocorrectionTypeNo];
    txtPassword.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [txtPassword setBackground:[UIImage imageNamed:@"textfild_bg"]];
    txtPassword.delegate=self;
    [txtPassword addTarget:self action:@selector(closeKeybard) forControlEvents:UIControlEventEditingDidEndOnExit];
    [txtPassword setSecureTextEntry:YES];
    
    //    [txtPassword setBorderStyle:UITextBorderStyleRoundedRect];
    [bgScrollView addSubview:txtPassword];
    
    UIButton *btnforgotPass=[[UIButton alloc] initWithFrame:CGRectMake(565, 378+_Y, 160, 35)];
    [btnforgotPass setTitle:@"忘记密码?" forState:UIControlStateNormal];
    btnforgotPass.titleLabel.font =[UIFont systemFontOfSize:33];
    [btnforgotPass setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnforgotPass setTitleColor:UIColorFromRGB(0xb70100) forState:UIControlStateNormal];
    [btnforgotPass setTitleColor:[UIColor darkGrayColor] forState:UIControlStateHighlighted];
    [btnforgotPass addTarget:self action:@selector(btnForgotPd) forControlEvents:UIControlEventTouchUpInside];
    [bgScrollView addSubview:btnforgotPass];
    
    UIButton *btnLogin=[[UIButton alloc] initWithFrame:CGRectMake(24, 450+_Y, 350, 104)];
    [btnLogin setTitle:@"登录" forState:UIControlStateNormal ];
    btnLogin.titleLabel.font =[UIFont systemFontOfSize:40];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    //    [btnLogin.layer setCornerRadius:3.0f];
    [btnLogin setBackgroundImage:[UIImage imageNamed:@"login_bg"] forState:UIControlStateNormal];
    [bgScrollView addSubview:btnLogin];
    
    UIButton *btnSign=[[UIButton alloc] initWithFrame:CGRectMake(394, 450+_Y, 350, 104)];
    [btnSign setTitle:@"注册" forState:UIControlStateNormal ];
    btnSign.titleLabel.font =[UIFont systemFontOfSize:40];
    [btnSign setTitleColor:UIColorFromRGB(0xb70100) forState:UIControlStateNormal];
    [btnSign setBackgroundImage:[UIImage imageNamed:@"register_bg"] forState:UIControlStateNormal];
    [btnSign addTarget:self action:@selector(registerClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [bgScrollView addSubview:btnSign];
    
    
    
}
-(void)btnReturnClick{
   
//    [self dismissModalViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark ----键盘---
//关闭键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.bgScrollView endEditing:YES];
}

- (void)closeKeybard
{
    [self.bgScrollView endEditing:YES];
}
/**
 开始编辑UITextField的方法
 */
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect textFrame =  textField.frame;
    float textY = textFrame.origin.y+textFrame.size.height;
    float bottomY = self.view.frame.size.height-textY;
    if(bottomY>=216)  //判断当前的高度是否已经有216，如果超过了就不需要再移动主界面的View高度
    {
        prewTag = -1;
        return;
    }
    prewTag = textField.tag;
    float moveY = 216-bottomY;
    prewMoveY = moveY;
    
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    frame.origin.y -=moveY;//view的Y轴上移
    frame.size.height +=moveY; //View的高度增加
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];//设置调整界面的动画效果
}

/**
 结束编辑UITextField的方法，让原来的界面还原高度
 */
-(void) textFieldDidEndEditing:(UITextField *)textField
{
    if(prewTag == -1) //当编辑的View不是需要移动的View
    {
        return;
    }
    float moveY ;
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    if(prewTag == textField.tag) //当结束编辑的View的TAG是上次的就移动
    {   //还原界面
        moveY =  prewMoveY;
        frame.origin.y +=moveY;
        frame.size. height -=moveY;
        self.view.frame = frame;
    }
    //self.view移回原位置
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    
    
}

//适应键盘高度
-(void)adaptKeyboardLocation:(NSNotification *)notification
{
    
    //NSLog(@"键盘高度即将变化");
    CGFloat keyBoardHeightDelta;
    //获取信件
    NSDictionary *info= notification.userInfo;
    //NSLog(@"通知携带的信息:%@",info);
    
    CGRect beginRect=[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endRect=[[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    //时间
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    keyBoardHeightDelta=beginRect.origin.y-endRect.origin.y;
    [UIView animateWithDuration:duration animations:^{
        //        [self.view setCenter:CGPointMake(self.view.center.x, self.view.center.y-keyBoardHeightDelta)];
        if ((beginRect.origin.y-endRect.origin.y)>0) {
            [self.bgScrollView setContentOffset:CGPointMake(0,50)];
        }else
            [self.bgScrollView setContentOffset:CGPointMake(0, 0)];
        
    }];
    
    
}

//注册事件
- (IBAction)registerClick:(UIButton *)sender
{
    self.registerViewController =[[MYRegisterViewController alloc] init];
    [self presentViewController:self.registerViewController animated:NO completion:nil];
    
}
//登录点击事件
-(IBAction)login:(UIButton *)sender{
    
    [self creatKey];
    
    if (txtLoginName.text.length==0||txtPassword.text.length==0) {
        mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        mbHud.labelText = @"用户名和密码不能为空";
        mbHud.mode = MBProgressHUDModeText;
        [self.view addSubview:mbHud];
        [mbHud showAnimated:YES whileExecutingBlock:^{
            sleep(1);
        } completionBlock:^{
            [mbHud removeFromSuperview];
            mbHud = nil;
        }];
    }else{
        mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        mbHud.labelText = @"登录中";
        
        [self.view addSubview:mbHud];
        mbHud.delegate = self;
        [mbHud showAnimated:YES whileExecutingBlock:^{
            NSString *strLogin =[NSString stringWithFormat:@"service=doLogin&userName=%@&password=%@",txtLoginName.text,txtPassword.text];
            loginService=[MYWebService new];
            loginDic = [loginService getDataSynWithKey:key encryptedString:strLogin appKey:nil];
        
            if (loginDic!=nil&&[[loginDic valueForKey:@"code"] integerValue]==1) {
                appKey = [loginDic valueForKey:@"appKey"];
                
                //获取帐户信息余额，是否认证；
                NSString *strQueryAcountInfoService=@"service=queryAcountInfo";
                accountDic = [NSDictionary new];
                accountDic = [loginService getDataSynWithKey:key encryptedString:strQueryAcountInfoService appKey:appKey];
                NSString *strPersonalInfoService=@"service=personalInfoService";
                userInformation = [loginService getDataSynWithKey:key encryptedString:strPersonalInfoService appKey:appKey];
                userRole = [[userInformation valueForKey:@"result"] valueForKey:@"role"];
                NSString *strGetBanksInfoService=@"service=getBanksInfoService&isDeduct=IS";
                bankDic = [loginService getDataSynWithKey:key encryptedString:strGetBanksInfoService appKey:appKey];
                
            }
            
            
        } completionBlock:^{
            [mbHud removeFromSuperview];
            if ([[loginDic valueForKey:@"code" ] integerValue]==0) {
                UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[loginDic valueForKey:@"message"] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [myAlert show];
            }else if ([[loginDic valueForKey:@"code"] integerValue]==1){
                if (loginFlag==false) {
//                    [self presentModalViewController:[MYRecommendViewController new] animated:YES];
                    [self presentViewController:[MYRecommendViewController new] animated:YES completion:nil];
                    
                }else if(loginFlag!=false){
//                    [self dismissModalViewControllerAnimated:NO];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }

            }else if ([[loginDic valueForKey:@"code"] integerValue]==2)
            {
                //                [self presentModalViewController:[MYRegInfoViewController new] animated:NO];
                [self presentViewController:[MYRegInfoViewController new] animated:YES completion:nil];
            }
            
        }];
     

        
        
/*
        NSString *strLogin =[NSString stringWithFormat:@"service=doLogin&userName=%@&password=%@",txtLoginName.text,txtPassword.text];
        loginService=[MYWebService new];
        NSDictionary *loginDic = [loginService getDataSynWithKey:key encryptedString:strLogin appKey:nil];
        NSString *appKey = [loginDic valueForKey:@"appKey"];
        if ([loginDic valueForKey:@"code"]) {
            
            //获取帐户信息余额，是否认证；
            NSString *strQueryAcountInfoService=@"service=queryAcountInfo";
            accountDic = [NSDictionary new];
            accountDic = [loginService getDataSynWithKey:@"asdfasdfsd" encryptedString:strQueryAcountInfoService appKey:appKey];
            //获取项目列表
            NSString *strIndexTrade=@"service=indexTrade&tradeType=2&pageSize=10&pageNo=1";
            indexTreadDic = [NSDictionary new];
            indexTreadDic = [loginService getDataSynWithKey:key encryptedString:strIndexTrade appKey:appKey];
            //获取用户个人信息，包括银行卡，名字
            NSString *strPersonalInfoService=@"service=personalInfoService";
            userInformation = [loginService getDataSynWithKey:key encryptedString:strPersonalInfoService appKey:appKey];

            [mbHud removeFromSuperview];
            [self presentViewController:[[MYRecommendViewController alloc]initWithNibName:nil bundle:nil] animated:NO completion:nil];
     
        }else{
            [mbHud removeFromSuperview];
            mbHud = [[MBProgressHUD alloc] initWithView:self.view];
            mbHud.labelText = @"登录失败";
            mbHud.mode = MBProgressHUDModeText;
            [self.view addSubview:mbHud];
            [mbHud show:YES];
            sleep(1);
        }
        */
    }
    
}
//生成随机16位字符 26 字母
-(void)creatKey{
    int NUMBER_OF_CHARS = 16;
    char data[NUMBER_OF_CHARS];
    for (int x=0;x<NUMBER_OF_CHARS;data[x++] = (char)('A' + (arc4random_uniform(26))));
    key =  [[NSString alloc] initWithBytes:data length:NUMBER_OF_CHARS encoding:NSUTF8StringEncoding];
    
}


#pragma mark -------------忘记密码--------
- (void)btnForgotPd
{
//    [self presentModalViewController:[ForgotPassWord new] animated:NO];
    [self presentViewController:[ForgotPassWord new] animated:YES completion:nil];
}



@end
